/**
 * 历史记录页面脚本
 */

class HistoryManager {
    constructor() {
        // 当前页码
        this.currentPage = 1;
        // 每页显示数量
        this.pageSize = 10;
        // 搜索关键词
        this.searchQuery = '';
        // 总页数
        this.totalPages = 1;
        
        // DOM元素
        this.historyList = document.getElementById('history-list');
        this.searchInput = document.getElementById('search-input');
        this.searchBtn = document.getElementById('search-btn');
        this.clearHistoryBtn = document.getElementById('clear-history-btn');
        this.prevPageBtn = document.getElementById('prev-page');
        this.nextPageBtn = document.getElementById('next-page');
        this.modal = document.getElementById('history-detail-modal');
        
        this.init();
    }
    
    // 初始化
    init() {
        // 加载历史记录
        this.loadHistory();
        
        // 绑定搜索事件
        if (this.searchInput && this.searchBtn) {
            this.searchBtn.addEventListener('click', () => {
                this.currentPage = 1;
                this.searchQuery = this.searchInput.value.trim();
                this.loadHistory();
            });
            
            // 回车搜索
            this.searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.currentPage = 1;
                    this.searchQuery = this.searchInput.value.trim();
                    this.loadHistory();
                }
            });
        }
        
        // 绑定清空历史记录事件
        if (this.clearHistoryBtn) {
            this.clearHistoryBtn.addEventListener('click', () => this.clearHistory());
        }
        
        // 绑定分页事件
        if (this.prevPageBtn) {
            this.prevPageBtn.addEventListener('click', () => {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadHistory();
                }
            });
        }
        
        if (this.nextPageBtn) {
            this.nextPageBtn.addEventListener('click', () => {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadHistory();
                }
            });
        }
        
        // 绑定历史记录项事件
        this.historyList.addEventListener('click', (e) => {
            const target = e.target;
            
            // 查看按钮
            if (target.classList.contains('view-btn')) {
                const id = target.getAttribute('data-id');
                this.viewHistoryDetail(id);
            }
            
            // 删除按钮
            if (target.classList.contains('delete-btn')) {
                const id = target.getAttribute('data-id');
                this.deleteHistoryItem(id);
            }
        });
        
        // 绑定模态框复制按钮事件
        const modalCopyBtn = document.getElementById('modal-copy-btn');
        if (modalCopyBtn) {
            modalCopyBtn.addEventListener('click', () => {
                const summaryContent = document.getElementById('modal-summary-content');
                if (summaryContent) {
                    utils.copyToClipboard(summaryContent.textContent)
                        .then(() => {
                            notificationSystem.show('摘要已复制到剪贴板', 'success');
                        })
                        .catch(() => {
                            notificationSystem.show('复制失败', 'error');
                        });
                }
            });
        }
    }
    
    // 加载历史记录
    async loadHistory() {
        try {
            loadingManager.show();
            
            const response = await apiService.getHistory(
                this.currentPage,
                this.pageSize,
                this.searchQuery
            );
            
            this.totalPages = Math.ceil(response.total / this.pageSize);
            this.updatePagination();
            this.renderHistoryList(response.items);
            
        } catch (error) {
            notificationSystem.show(error.message, 'error');
        } finally {
            loadingManager.hide();
        }
    }
    
    // 渲染历史记录列表
    renderHistoryList(items) {
        if (!this.historyList) return;
        
        if (items.length === 0) {
            this.historyList.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">📜</div>
                    <p>${this.searchQuery ? '未找到相关历史记录' : '暂无历史记录'}</p>
                </div>
            `;
            return;
        }
        
        this.historyList.innerHTML = items.map(item => `
            <div class="history-item" data-id="${item.id}">
                <div class="history-item-header">
                    <div class="history-item-title">
                        ${item.文件名 
                            ? `<span class="file-icon">📄</span> ${item.文件名}`
                            : `<span class="text-icon">📝</span> 文本摘要`
                        }
                    </div>
                    <div class="history-item-date">${utils.formatDate(item.日期)}</div>
                </div>
                <div class="history-item-summary">${item.摘要.substring(0, 100)}...</div>
                <div class="history-item-footer">
                    <div class="history-item-info">
                        <span class="badge">比例: ${item.比例 * 100}%</span>
                        <span class="badge">关键词: ${item.关键词.length}</span>
                    </div>
                    <div class="history-item-actions">
                        <button class="btn small view-btn" data-id="${item.id}">查看</button>
                        <button class="btn small danger delete-btn" data-id="${item.id}">删除</button>
                    </div>
                </div>
            </div>
        `).join('');
    }
    
    // 更新分页
    updatePagination() {
        const pageInfo = document.querySelector('.page-info');
        if (pageInfo) {
            pageInfo.textContent = `第 ${this.currentPage} 页，共 ${this.totalPages} 页`;
        }
        
        if (this.prevPageBtn) {
            this.prevPageBtn.disabled = this.currentPage <= 1;
        }
        
        if (this.nextPageBtn) {
            this.nextPageBtn.disabled = this.currentPage >= this.totalPages;
        }
    }
    
    // 查看历史记录详情
    async viewHistoryDetail(id) {
        try {
            loadingManager.show();
            
            const detail = await apiService.getHistoryDetail(id);
            
            // 更新模态框内容
            document.getElementById('modal-summary-content').textContent = detail.摘要;
            document.getElementById('modal-keywords-content').innerHTML = detail.关键词
                .map(word => `<span class="keyword-tag">${word}</span>`)
                .join('');
            document.getElementById('modal-original-content').textContent = detail.原文;
            
            // 显示模态框
            modalSystem.openModal('history-detail-modal');
            
        } catch (error) {
            notificationSystem.show(error.message, 'error');
        } finally {
            loadingManager.hide();
        }
    }
    
    // 删除历史记录项
    async deleteHistoryItem(id) {
        if (!confirm('确定要删除这条历史记录吗？')) {
            return;
        }
        
        try {
            loadingManager.show();
            
            await apiService.deleteHistory(id);
            
            // 重新加载当前页
            // 如果当前页已空，且不是第一页，则加载上一页
            const currentItems = this.historyList.querySelectorAll('.history-item');
            if (currentItems.length === 1 && this.currentPage > 1) {
                this.currentPage--;
            }
            
            await this.loadHistory();
            
            notificationSystem.show('删除成功', 'success');
            
        } catch (error) {
            notificationSystem.show(error.message, 'error');
        } finally {
            loadingManager.hide();
        }
    }
    
    // 清空历史记录
    async clearHistory() {
        if (!confirm('确定要清空所有历史记录吗？此操作不可恢复！')) {
            return;
        }
        
        try {
            loadingManager.show();
            
            await apiService.clearHistory();
            
            this.currentPage = 1;
            await this.loadHistory();
            
            notificationSystem.show('历史记录已清空', 'success');
            
        } catch (error) {
            notificationSystem.show(error.message, 'error');
        } finally {
            loadingManager.hide();
        }
    }
}

// 初始化历史记录管理器
document.addEventListener('DOMContentLoaded', () => {
    new HistoryManager();
});